package ca.llsutherland.nfl.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.nfl.domain.User;
import ca.llsutherland.nfl.exception.ValidationException;
import ca.llsutherland.nfl.util.StringUtil;

public class UserDao extends BaseDao {

	private static UserDao instance = new UserDao();
	
	@Override
    public String getUnderlyingTableName() {
        return "USER";
    }
	
	public static UserDao getInstance() {
        return instance ;
    }

	public User create(User user) {
		String sql = "INSERT INTO USER (USERNAME, PASSWORD, IS_BLOCKED, HAS_PAID, ROLE_ID) VALUES ("
            + StringUtil.addSingleQuotes(user.getUsername()) + ", "
            + StringUtil.addSingleQuotes(user.getPassword()) + ", " 
            + user.isBlocked() + ", " 
            + user.isPaid() + ", " 
            + user.getRole().getId() + ");";
        return findById(super.create(sql));
    }
	
	public User findById(Long id) {
        String findByIdQuery = getFindByIdQuery(id);
        return buildUser(findByIdQuery);
    }
	
	private User buildUser(String sql) {
        User user = null;
        ResultSet rs = super.findByQuery(sql);
        
        try {
            if(rs.next()){
                user = new User();
                user.setId(Long.valueOf(rs.getLong("ID")));
                user.setUsername(rs.getString("USERNAME"));
                user.setPassword(rs.getString("PASSWORD"));
                user.setBlocked(rs.getBoolean("IS_BLOCKED"));
                user.setPaid(rs.getBoolean("HAS_PAID"));
                user.setId(Long.valueOf(rs.getLong("ID")));
                user.setRole(RoleDao.getInstance().findById(Long.valueOf(rs.getLong("ROLE_ID"))));
            }
            rs.close();
        } catch (SQLException e) {
            throw new ValidationException(e.getMessage() + " in buildUser()");
        } finally {
            rs = null;            
        }
        return user;
    }
}
